package com.kjsdfgk.hjmdsf.live.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.kjsdfgk.hjmdsf.live.di.component.DaggerLiveHomeComponent;
import com.kjsdfgk.hjmdsf.live.mvp.bean.PingtaiBean;
import com.kjsdfgk.hjmdsf.live.mvp.bean.VersionEntity;
import com.kjsdfgk.hjmdsf.live.mvp.contract.LiveHomeContract;
import com.kjsdfgk.hjmdsf.live.mvp.presenter.LiveHomePresenter;
import com.lksdkjs.live.R;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/10/2020 11:37
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class LiveHomeActivity extends BaseActivity<LiveHomePresenter> implements LiveHomeContract.View, SwipeRefreshLayout.OnRefreshListener {

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiveHomeComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_live_home; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.live_tips)
    TextView liveTips;



    LiveAdapter mAdapter;

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        toolbarBack.setVisibility(View.INVISIBLE);
        mPresenter.getPingTaiJson();
        mPresenter.checkVersion();
        mSwipeRefreshLayout.setOnRefreshListener(this);
        final GridLayoutManager mLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(mLayoutManager);
        GridLineItemDecoration mDecor = new GridLineItemDecoration(this, 0xFFe1e1e1, 3, 1);
        mRecyclerView.addItemDecoration(mDecor);
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);


        if (AVUser.getCurrentUser() == null || true) {
            String android = "live"+ DeviceMessageUtil.getAndroidId(this );
//           String imei =  DeviceMessageUtil.getEI_SI("imei" ,this );
            if (android == null){
                SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-mm-dd-HH:mm:ss");
                //2019年的第133天。占位符是特定的
                //要格式化的Date对象
                Date date=new Date();
                //使用format()方法格式化Date对象为字符串，返回字符串

                android = sdf1.format(date) ;
            }
            AVUser user = new AVUser();// 新建 AVUser 对象实例
            user.setUsername(android);// 设置用户名
            user.setPassword(android);// 设置密码
            user.put("info" , DeviceMessageUtil.getDeviceInfo(this));
            user.signUpInBackground().subscribe(new Observer<AVUser>() {
                @Override
                public void onSubscribe(Disposable d) {

                }
                @Override
                public void onNext(AVUser avUser) {
                    Timber.tag(TAG).d(avUser.toJSONString());
                }
                @Override
                public void onError(Throwable e) {
                    Timber.tag(TAG).d(e.toString());
                }
                @Override
                public void onComplete() {

                }
            });
        }
    }

    @Override
    public void showLoading(String key) {
        mSwipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public boolean isCancel() {
        return loadingDialog.isCancel(null);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void onRefresh() {
        mPresenter.getPingTaiJson();
    }

    @Override
    public void showPingTaiJson(List<PingtaiBean> datas) {
        mRecyclerView.setAdapter(mAdapter = new LiveAdapter(datas));
      //  liveTips.setVisibility(View.VISIBLE);
    }

    @Override
    public void showNewVersion(VersionEntity updateVersion) {
        QMUIDialog.MessageDialogBuilder builder = new QMUIDialog.MessageDialogBuilder(this);
        builder.setTitle("发现新版本--v" + updateVersion.getVersionName());
        builder.setMessage(updateVersion.getUpdateMessage());
        builder.addAction("立即更新", (dialog, index) -> {
//            showMessage("开始下载", TastyToast.INFO);
//            Intent intent = new Intent(MainActivity.this, UpdateDownloadService.class);
//            intent.putExtra("updateVersion", updateVersion);
//            startService(intent);
            Intent intent= new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(updateVersion.getApkDownloadUrl());
            intent.setData(content_url);
            startActivity(intent);

        });
  /*      builder.addAction("稍后更新", (dialog, index) -> dialog.dismiss());
        builder.addAction("该版本不再提示", (dialog, index) -> {
            //保存版本号，用户对于此版本选择了不在提示
            presenter.setIgnoreUpdateVersionCode(updateVersion.getVersionCode());
            dialog.dismiss();
        });*/
        builder.setCancelable(false);
        builder.setCanceledOnTouchOutside(false);
        builder.show();
    }

    @Override
    public void onBackPressedSupport() {

    }

    private boolean isOnKeyBacking = false;
    private final Handler mainLoopHandler = new Handler(Looper.getMainLooper());
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isOnKeyBacking) {
                mainLoopHandler.removeCallbacks(onBackTimeThread);
                isOnKeyBacking = false;
                finish();
            }else {
                isOnKeyBacking = true;
                Toast.makeText(this, "再按一下退出", Toast.LENGTH_SHORT).show();
                mainLoopHandler.postDelayed(onBackTimeThread, 2000);
            }
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
    private final Runnable onBackTimeThread = new Runnable(){
        public void run() {
            isOnKeyBacking = false;
        }
    };
}
